package tgc.edu.tms.web.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.tms.custom.AjaxResult;
import tgc.edu.tms.custom.CommonController;
import tgc.edu.tms.custom.ExportExcel;
import tgc.edu.tms.custom.TimeUtils;
import tgc.edu.tms.entity.Schedule;
import tgc.edu.tms.entity.Teacher;
import tgc.edu.tms.entity.Teachingplan;
import tgc.edu.tms.security.UserUtils;
import tgc.edu.tms.service.ScheduleService;
import tgc.edu.tms.service.TeacherService;
import tgc.edu.tms.service.TeachingplanService;
import tgc.edu.tms.web.form.TeachingplanForm;

@Controller
@RequestMapping(value = "/teachingplan")
public class TeachingplanController extends CommonController<Teachingplan, Integer, TeachingplanForm> {

	@Autowired
	private TeachingplanService service;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private ScheduleService scheduleService;
	@Autowired
	private UserUtils userUtils;

	@Override
	public void edit(TeachingplanForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		Teacher user = (Teacher) userUtils.getUser();
		List<Schedule> list1 = new ArrayList<>();
		List<Schedule> list = scheduleService.findAll(buildSpec2());
		String kcmc = null;
		for (Schedule schedule : list) {
			if(kcmc==null) {
				list1.add(schedule);
			}else {	
				if(!kcmc.equals(schedule.getKcmc())) {
					list1.add(schedule);
				}
			}
			kcmc = schedule.getKcmc();
		}
		map.put("list", list1);
		map.put("user", user);
		map.put("xq", TimeUtils.getxq());
		super.edit(form, map);
	}

	@Override
	public void manage(ModelMap map) {
		List<Schedule> list1 = new ArrayList<>();
		List<Schedule> list = scheduleService.findAll(buildSpec2());
		String kcmc = null;
		for (Schedule schedule : list) {
			if(kcmc==null) {
				list1.add(schedule);
			}else {	
				if(!kcmc.equals(schedule.getKcmc())) {
					list1.add(schedule);
				}
			}
			kcmc = schedule.getKcmc();
		}
		map.put("list", list1);
		super.manage(map);
	}

	/**
	 * 导出报表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/export")
	@ResponseBody
	public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<Teachingplan> list = service.findAll(buildSpec1());
		String title = "上课计划表";
		String[] columnName = new String[] { "序号","学期", "周次", "课次", "教师", "课程", "上课内容" };
		List<Object[]> dataList = new ArrayList<Object[]>();
		for (Teachingplan t : list) {
			String xq = t.getXq();
			String zc = t.getZc();
			String classes = t.getClasses();
			String teacher = t.getTeacherName();
			String kcmc = t.getName();
			String content = t.getContent();
			Object[] objs = { xq, xq, zc, classes, teacher, kcmc, content };
			dataList.add(objs);
		}
		// 实例化工具类
		ExportExcel ex = new ExportExcel(title, columnName, dataList, request, response);
		try {
			// 导出excel
			ex.export();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/***
	 * page查询所用的安全查询
	 */
	@Override
	public Specification<Teachingplan> buildSpec(TeachingplanForm form) {
		Specification<Teachingplan> specification = new Specification<Teachingplan>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Teachingplan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				String curriculum = form.getCurriculum();
				if (StringUtils.hasText(curriculum)) {
					rules.add(cb.equal(root.get("curriculum"), curriculum));
				}
				String xq = form.getXq();
				if (StringUtils.hasText(xq)) {
					rules.add(cb.like(root.get("xq"), "%"+xq+"%"));
				}
				String zc = form.getZc();
				if (StringUtils.hasText(zc)) {
					rules.add(cb.equal(root.get("zc"), zc));
				}
				String classes = form.getClasses();
				if (StringUtils.hasText(classes)) {
					rules.add(cb.equal(root.get("classes"), classes));
				}
				rules.add(cb.equal(root.get("teacher").get("id"), userUtils.getUser().getId()));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;

	}
	public Specification<Schedule> buildSpec2() {
		Specification<Schedule> specification = new Specification<Schedule>() {
			
			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<Schedule> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate Predicate = cb.equal(root.get("teacher"), userUtils.getUser().getName());
				return Predicate;
			}
			
		};
		
		return specification;
		
	}

	public Specification<Teachingplan> buildSpec1() {
		Specification<Teachingplan> specification = new Specification<Teachingplan>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Teachingplan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate Predicate = cb.equal(root.get("teacher").get("id"), userUtils.getUser().getId());
				return Predicate;
			}

		};

		return specification;

	}

	@Override
	public Object save(TeachingplanForm form) {
		try {
			Teachingplan model = new Teachingplan();
			Integer id = form.getId();
			if (id != null) {
				model = service.findById(id);
			}
			BeanUtils.copyProperties(form, model, "id");
			Teacher teacher = teacherService.findById(form.getTeacher().getId());
			model.setTeacher(teacher);
			service.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false, "数据保存失败");
		}
	}

}
